﻿Imports System.Web.Configuration
Imports System.Net
Imports System.IO
Imports System.Xml
Imports System.ComponentModel

Namespace MDT_MonitoringService_MVCDemo
    Public Class MDTMonitorEventController
        Inherits System.Web.Mvc.Controller

        Private logger As NLog.Logger = NLog.LogManager.GetCurrentClassLogger()
        Private _DefaultProperties As New Dictionary(Of String, String)
        Private _CustomProperties As New Dictionary(Of String, String)


        ''' <summary>
        ''' consumes the MDT Monitoring data.
        ''' Forwards information to original MDT Monitoring Web service.
        ''' </summary>
        ''' <param name="DefaultProps"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Function PostEvent(DefaultProps As MDTDefaultMonitoringModel) As ActionResult

            If Not String.IsNullOrEmpty(DefaultProps.computerName) Then

                ' Forward information to original MDT service if the URL is specified
                Try
                    Dim param As String = String.Empty

                    ' Prepare parameter string
                    For Each prop As PropertyDescriptor In TypeDescriptor.GetProperties(DefaultProps)
                        ' Fill a dictionary with all default MDT properties for performance reasons
                        _DefaultProperties.Add(prop.Name, prop.GetValue(DefaultProps))
                        param &= String.Format("&{0}={1}", prop.Name, HttpUtility.UrlEncode(_DefaultProperties(prop.Name)))
                    Next

                    ' Remove inital "&" if necessary
                    param = Mid(param, 1)

                    ' Prepare URL
                    Dim BaseURL As String = WebConfigurationManager.AppSettings("MDTMonitoringURL") & "/MDTMonitorEvent/PostEvent?"
                    Dim URL As New Uri(BaseURL & param)

                    ' Send data 
                    Dim client As WebClient = New WebClient()
                    Dim data As Stream = client.OpenRead(URL)

                    ' Read uniqueID from MDT
                    Dim reader As StreamReader = New StreamReader(data)
                    Dim MDTXMLResult As XmlDocument = New XmlDocument

                    Dim xmlString As String = reader.ReadToEnd
                    reader.Close()
                    MDTXMLResult.LoadXml(xmlString)
                    If MDTXMLResult.ChildNodes.Count > 0 Then
                        DefaultProps.uniqueID = MDTXMLResult.ChildNodes(0).InnerText
                    End If


                Catch exc As Exception
                    Trace.WriteLine("Exception: " & exc.Message)
                End Try


                ' Make sure we have a unique ID for this deployment
                If String.IsNullOrEmpty(DefaultProps.uniqueID) Then
                    DefaultProps.uniqueID = Guid.NewGuid.ToString
                End If


                ' Get additional custom properties
                For Each prop In Request.QueryString.Keys
                    If Not _DefaultProperties.ContainsKey(prop) Then
                        _CustomProperties.Add(prop, Request.QueryString(prop))
                    End If
                Next

                ' Log the information for demonstration purposes
                logger.Info("{0} - {1} ({2}/{3}) - {4} ({5}) - {6}", DefaultProps.computerName, DefaultProps.stepName, DefaultProps.currentStep, DefaultProps.totalSteps, DefaultProps.message, DefaultProps.messageId, DefaultProps.uniqueID)

            End If

            ' Return the unique ID
            Return New XmlResult(DefaultProps.uniqueID)
        End Function


        ''' <summary>
        ''' Returns a list of assigned settings for the specified computer
        ''' </summary>
        ''' <param name="uniqueID">Deployment ID</param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Function GetSettings(uniqueID As String) As ActionResult

            Return New XmlResult(New GetSettingsResultModel With {.MonitorResult = "HelloWorld"})
        End Function



        Function Index() As ActionResult
            Return New ContentResult()
        End Function
    End Class
End Namespace